/**
 * 
 */
package com.cn.daifaming.demoservice.sharding.algorithm;

import java.util.Collection;
import java.util.LinkedHashSet;

import com.dangdang.ddframe.rdb.sharding.api.ShardingValue;
import com.dangdang.ddframe.rdb.sharding.api.strategy.table.SingleKeyTableShardingAlgorithm;
import com.google.common.collect.Range;

/**
 * @author Administrator
 *
 */
public class MySingleKeyTableShardingAlgorithm implements SingleKeyTableShardingAlgorithm<String>
{
	/**
     * sql 中 = 操作时，table的映射
     */
    public String doEqualSharding(Collection<String> tableNames, ShardingValue<String> shardingValue)
    {
        for (String each : tableNames)
        {
            String value = shardingValue.getValue();
            if (each.endsWith(Integer.valueOf(value) % 2 + ""))
            {
                return each;
            }
        }
        throw new IllegalArgumentException();
    }
    /**
     * sql 中 in 操作时，table的映射
     */
    public Collection<String> doInSharding(Collection<String> tableNames, ShardingValue<String> shardingValue)
    {
        Collection<String> result = new LinkedHashSet<String>(tableNames.size());
        for (String value : shardingValue.getValues())
        {
            for (String tableName : tableNames)
            {
                if (tableName.endsWith(Integer.valueOf(value) % 2 + ""))
                {
                    result.add(tableName);
                }
            }
        }
        return result;
    }
    /**
     * sql 中 between 操作时，table的映射
     */
    public Collection<String> doBetweenSharding(Collection<String> tableNames, ShardingValue<String> shardingValue)
    {
        Collection<String> result = new LinkedHashSet<String>(tableNames.size());
        Range<String> range = (Range<String>) shardingValue.getValueRange();
        Integer lowerEndpoint = Integer.valueOf(range.lowerEndpoint());
        Integer upperEndpoint = Integer.valueOf(range.upperEndpoint());
        for (Integer i = lowerEndpoint; i <= upperEndpoint; i++)
        {
            for (String each : tableNames)
            {
                if (each.endsWith(i % 2 + ""))
                {
                    result.add(each);
                }
            }
        }
        return result;
    }
}
